function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get.bind(); } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { Node, Edge } from '@antv/x6';
import ELNode from "./node";
import { ConditionTypeEnum, LITEFLOW_EDGE, NODE_TYPE_END, NODE_TYPE_START } from "../constant";
import { ThenOperator } from "./el";

/**
 * EL表达式的根节点——EL表达式的所有延伸内容，都是在根节点上开始的。
 * 例如一个串行编排(THEN)：
 * (1) EL表达式形式：THEN(a, b, c, d)
 * (2) JSON表示形式：
 * {
    type: ConditionTypeEnum.THEN,
    children: [
      { type: NodeTypeEnum.COMMON, id: 'a' },
      { type: NodeTypeEnum.COMMON, id: 'b' },
      { type: NodeTypeEnum.COMMON, id: 'c' },
      { type: NodeTypeEnum.COMMON, id: 'd' },
    ],
  }
 * (3) 通过ELNode节点模型进行表示的组合关系为：
                                          ┌─────────────────┐
                                      ┌──▶│  NodeOperator   │
                                      │   └─────────────────┘
                                      │   ┌─────────────────┐
                                      ├──▶│  NodeOperator   │
  ┌─────────┐    ┌─────────────────┐  │   └─────────────────┘
  │  Chain  │───▶│  ThenOperator   │──┤   ┌─────────────────┐
  └─────────┘    └─────────────────┘  ├──▶│  NodeOperator   │
                                      │   └─────────────────┘
                                      │   ┌─────────────────┐
                                      └──▶│  NodeOperator   │
                                          └─────────────────┘
 */
var Chain = /*#__PURE__*/function (_ELNode) {
  _inherits(Chain, _ELNode);
  var _super = _createSuper(Chain);
  function Chain(children) {
    var _this;
    _classCallCheck(this, Chain);
    _this = _super.call(this);
    _defineProperty(_assertThisInitialized(_this), "type", ConditionTypeEnum.CHAIN);
    _defineProperty(_assertThisInitialized(_this), "children", []);
    _defineProperty(_assertThisInitialized(_this), "startNode", void 0);
    _defineProperty(_assertThisInitialized(_this), "endNode", void 0);
    if (children) {
      _this.children = children;
    }
    return _this;
  }

  /**
   * 转换为X6的图数据格式
   */
  _createClass(Chain, [{
    key: "toCells",
    value: function toCells() {
      this.resetCells();
      var cells = this.cells;
      // 1. 首先：添加一个开始节点
      var start = Node.create({
        shape: NODE_TYPE_START,
        attrs: {
          label: {
            text: '开始'
          }
        }
      });
      start.setData({
        model: this,
        toolbar: {
          prepend: false,
          append: true,
          delete: false,
          replace: false
        }
      }, {
        overwrite: true
      });
      cells.push(start);
      this.startNode = start;

      // 2. 其次：解析已有的节点
      var last = start;
      this.children.forEach(function (x) {
        x.toCells();
        cells.push(Edge.create({
          shape: LITEFLOW_EDGE,
          source: last.id,
          target: x.getStartNode().id
        }));
        last = x.getEndNode();
      });

      // 3. 最后：添加一个结束节点
      var end = Node.create({
        shape: NODE_TYPE_END,
        attrs: {
          label: {
            text: '结束'
          }
        }
      });
      end.setData({
        model: this,
        toolbar: {
          prepend: true,
          append: false,
          delete: false,
          replace: false
        }
      }, {
        overwrite: true
      });
      cells.push(end);
      this.endNode = end;
      cells.push(Edge.create({
        shape: LITEFLOW_EDGE,
        source: last.id,
        target: end.id
      }));
      return this.getCells();
    }

    /**
     * 转换为EL表达式字符串
     */
  }, {
    key: "toEL",
    value: function toEL() {
      var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      return "".concat(this.dataPropertyToEL(prefix)).concat(this.children.map(function (x) {
        return x.toEL(prefix);
      }).join(', '), ";");
    }
  }, {
    key: "dataPropertyToEL",
    value: function dataPropertyToEL() {
      var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
      var dataProperties = [];
      var next = [this];
      var _loop = function _loop() {
        var current = [];
        next.forEach(function (item) {
          var _properties$data, _properties$data2;
          var properties = item.getProperties();
          if ((_properties$data = properties.data) !== null && _properties$data !== void 0 && _properties$data.name && (_properties$data2 = properties.data) !== null && _properties$data2 !== void 0 && _properties$data2.value) {
            dataProperties.push(properties.data);
          }
          if (item.condition) {
            current.push(item.condition);
          }
          if (item.children && item.children.length) {
            current = current.concat(item.children);
          }
        });
        next = current;
      };
      while (next.length) {
        _loop();
      }
      return dataProperties.map(function (dataProperty) {
        return "".concat(prefix).concat(dataProperty.name || '', "=").concat(dataProperty.value || '', ";\n");
      }).join('');
    }

    /**
     * 转换为JSON格式
     */
  }, {
    key: "toJSON",
    value: function toJSON() {
      if (this.children.length) {
        if (this.children.length === 1) {
          return this.children[0].toJSON();
        } else {
          return this.children.map(function (child) {
            return child.toJSON();
          });
        }
      }
      return {};
    }

    /**
     * 在开始节点的后面、插入新节点
     * @param newNode 新节点
     * @returns
     */
  }, {
    key: "append",
    value: function append(newNode) {
      if (this.children.length === 1) {
        if (this.children[0].type === ConditionTypeEnum.THEN) {
          return this.children[0].prependChild(newNode, 0);
        }
      }
      return this.appendChild(newNode, 0);
    }

    /**
     * 在后面添加子节点
     * @param newNode 子节点
     * @param index 指定位置：可以是索引，也可以是兄弟节点
     */
  }, {
    key: "appendChild",
    value: function appendChild(newNode, index) {
      var result = _get(_getPrototypeOf(Chain.prototype), "appendChild", this).call(this, newNode, index);
      this.addWrapperIfPossible();
      return result;
    }

    /**
     * 在结束节点的前面、插入新节点
     * @param child 新节点
     * @returns
     */
  }, {
    key: "prepend",
    value: function prepend(newNode) {
      if (this.children.length === 1) {
        if (this.children[0].type === ConditionTypeEnum.THEN) {
          return this.children[0].appendChild(newNode);
        }
      }
      return this.appendChild(newNode);
    }

    /**
     * 在后面添加子节点
     * @param newNode 子节点
     * @param index 指定位置：可以是索引，也可以是兄弟节点
     */
  }, {
    key: "prependChild",
    value: function prependChild(newNode, index) {
      var result = _get(_getPrototypeOf(Chain.prototype), "prependChild", this).call(this, newNode, index);
      this.addWrapperIfPossible();
      return result;
    }

    /**
     * 对于根节点，添加超过一个的新节点，则自动包一个THEN
     */
  }, {
    key: "addWrapperIfPossible",
    value: function addWrapperIfPossible() {
      if (this.children.length > 1) {
        var wrapper = new ThenOperator(this, []);
        this.children.forEach(function (child) {
          wrapper.appendChild(child);
        });
        this.children = [wrapper];
      }
    }

    /**
     * 根节点不允许删除
     */
  }, {
    key: "remove",
    value: function remove() {
      return false;
    }
  }]);
  return Chain;
}(ELNode);
export { Chain as default };